package com.ruoyi.learn.java.collection;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Map;
import java.util.Set;

public class HashtableDemo {
    public static void main(String[] args) {
        // Create a Hashtable to store employee IDs and names
        Hashtable<Integer, String> employeeTable = new Hashtable<>();

        // Adding elements to the Hashtable
        employeeTable.put(101, "John Doe");
        employeeTable.put(102, "Jane Smith");
        employeeTable.put(103, "Bob Johnson");
        employeeTable.put(104, "Alice Williams");

        System.out.println("Initial Hashtable: " + employeeTable);

        // Retrieving values using get()
        String employeeName = employeeTable.get(102);
        System.out.println("\nEmployee with ID 102: " + employeeName);

        // Checking if a key exists
        boolean hasKey = employeeTable.containsKey(103);
        System.out.println("Contains key 103? " + hasKey);

        // Checking if a value exists
        boolean hasValue = employeeTable.containsValue("Bob Johnson");
        System.out.println("Contains value 'Bob Johnson'? " + hasValue);

        // Getting the size of the Hashtable
        System.out.println("Size of Hashtable: " + employeeTable.size());

        // Removing an element
        employeeTable.remove(104);
        System.out.println("\nHashtable after removing ID 104: " + employeeTable);

        // Iterating using keySet()
        System.out.println("\nIterating using keySet():");
        Set<Integer> keys = employeeTable.keySet();
        for (Integer key : keys) {
            System.out.println("ID: " + key + ", Name: " + employeeTable.get(key));
        }

        // Iterating using entrySet()
        System.out.println("\nIterating using entrySet():");
        Set<Map.Entry<Integer, String>> entries = employeeTable.entrySet();
        for (Map.Entry<Integer, String> entry : entries) {
            System.out.println("ID: " + entry.getKey() + ", Name: " + entry.getValue());
        }

        // Using Enumeration to iterate over keys
        System.out.println("\nIterating using Enumeration (keys):");
        Enumeration<Integer> keyEnum = employeeTable.keys();
        while (keyEnum.hasMoreElements()) {
            Integer key = keyEnum.nextElement();
            System.out.println("ID: " + key + ", Name: " + employeeTable.get(key));
        }

        // Clearing the Hashtable
        employeeTable.clear();
        System.out.println("\nHashtable after clear(): " + employeeTable);
        System.out.println("Is Hashtable empty? " + employeeTable.isEmpty());
    }
}

